var crypto = require('crypto'),
    fs = require('fs'),
    //封装打开数据库获取信息的方法
    User = require('../models/user.js'),//获取用户信息
    Post = require('../models/post.js'),//获取文章信息
    Barrage = require('../models/Barrage.js'),//获取弹幕信息
    Comment = require('../models/comment.js');//获取留言信息

module.exports = function(app) {

  //主页
  app.get('/', function (req, res) {
    //取出最新一页的数据
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //查询并返回第 page 页的 3 篇文章(不足则全部获取)
    Post.getThree(null, page, function (err, posts, total) {
      if (err) {
        posts = [];
      }
      //加载数据进主页，并返回成功或错误信息
      res.render('index', {
        title: '主页-最新',
        posts: posts,
        page: page,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.get('/hot', function (req, res) {
    //取出最新一页的数据
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //查询并返回第 page 页的 3 篇文章(不足则全部获取)
    Post.getThreeHot(null, page, function (err, posts, total) {
      if (err) {
        posts = [];
      }
      //加载数据进主页，并返回成功或错误信息
      res.render('hot', {
        title: '主页-热门',
        posts: posts,
        page: page,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.get('/more', function (req, res) {
    //判断是否是第一页，并把请求的页数转换成 number 类型
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //查询并返回第 page 页的  5篇文章（不足则全部获取）
    Post.getFive(null, page, function (err, posts, total) {
      if (err) {
        posts = [];
      }
      res.render('more', {
        title: '主页-更多',
        posts: posts,
        page: page,
        isFirstPage: (page - 1) === 0,
        isLastPage: ((page - 1) * 5 + posts.length) === total,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //进入弹幕页
  app.get('/barrage', function (req, res) {
    Barrage.get(function (err, post) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      res.render('barrage', {
        title: '弹幕',
        post:post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //动弹保存
  app.post('/barrage', function (req, res) {
    User.get(req.session.user.name, function (err, user) {
      //定义留言数据格式
      var date = new Date(),
          time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
               date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
      var barrage = {
        name: user.name,
        email: user.email,
        website: '/u/' + user.name,
        time: time,
        content: req.body.content
    }
    var newBarrage = new Barrage(barrage);
    //将新的留言信息存入数据库
    newBarrage.save(function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '动弹成功!');
      res.redirect('back');//成功，返回上一步操作，并重新加载留言数据
    });
    });
  });

  //注册页
  app.get('/reg', checkNotLogin);
  app.get('/reg', function (req, res) {
    res.render('reg', {
      title: '注册',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/reg', checkNotLogin);
  app.post('/reg', function (req, res) {
    var password = req.body.password,
        password_re = req.body['password-repeat'];
    //检验用户两次输入的密码是否一致
    if (password_re !== password) {
      req.flash('error', '两次输入的密码不一致!'); 
      return res.redirect('/reg');//返回注册页
    }
    //生成密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    var newUser = new User({
        name: req.body.name,
        password: password,
        email: req.body.email
    });
    //检查用户名是否已经存在 
    User.get(newUser.name, function (err, user) {
      if (user) {
        req.flash('error', '用户已存在!');
        return res.redirect('/reg');//返回注册页
      }
      //如果不存在则新增用户
      newUser.save(function (err, user) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/reg');//注册失败返回主册页
        }
        req.session.user = user;//用户信息存入 session
        req.flash('success', '注册成功!');
        res.redirect('/login');//注册成功后跳转登陆页
      });
    });
  });

  //修改密码页
  app.get('/change', checkLogin);
  app.get('/change', function (req, res) {
    res.render('change', {
      title: '修改密码',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/change', checkLogin);
  app.post('/change', function (req, res) {
    var ypassword = req.body.ypw,
        password = req.body.xpw,
        password_re = req.body['xpw-2'];

    //检验用户两次输入的密码是否一致
    if (password_re !== password) {
      req.flash('error', '两次输入的密码不一致!'); 
      return res.redirect('/change');//返回修改页
    }
    //生成原始密码的 md5 值
    var md5 = crypto.createHash('md5');
    ypassword = md5.update(req.body.ypw).digest('hex');
    //检查密码是否正确
    User.get(req.session.user.name, function (err, user) {
      if (ypassword !== user.password) {
        req.flash('error', '原始密码错误!');
        return res.redirect('/change');//返回修改页
      }
    //生成新密码的 md5 值
    var md5 = crypto.createHash('md5');
    password = md5.update(req.body.xpw).digest('hex');
    //更新数据库，密码
    User.update(user.name, password, function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/change');//出错！返回修改页
      }
      req.flash('success', '修改成功!');
      res.redirect('/');//成功！返回主页
    });

    });
  });

  //登陆页
  app.get('/login', checkNotLogin);
  app.get('/login', function (req, res) {
    res.render('login', {
      title: '登陆',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/login', checkNotLogin);
  app.post('/login', function (req, res) {
    //生成密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    //检查用户是否存在
    User.get(req.body.name, function (err, user) {
      if (!user) {
        req.flash('error', '用户不存在!'); 
        return res.redirect('/login');//用户不存在则跳转到登陆页
      }
      //检查密码是否一致
      if (user.password !== password) {
        req.flash('error', '密码错误!'); 
        return res.redirect('/login');//密码错误则跳转到登陆页
      }
      //用户名密码都匹配后，将用户信息存入 session
      req.session.user = user;
      req.flash('success', '登陆成功!');
      res.redirect('/');//登陆成功后跳转到主页
    });
  });

  //发表文章页
  app.get('/post', checkLogin);
  app.get('/post', function (req, res) {
    res.render('post', {
      title: '发表',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/post', checkLogin);
  app.post('/post', function (req, res) {
    var currentUser = req.session.user,
        tags = [req.body.tag1, req.body.tag2, req.body.tag3],
        post = new Post(currentUser.name, req.body.title, tags, req.body.post);
    post.save(function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/post');//发表失败返回发表页
      }
      req.flash('success', '发布成功!');
      res.redirect('/');//发表成功跳转到主页
    });
  });

  //登出页
  app.get('/logout', checkLogin);//检查是否登录，未登陆返回登陆页
  app.get('/logout', function (req, res) {
    req.session.user = null;
    req.flash('success', '登出成功!');
    res.redirect('/');//登出成功后跳转到主页
  });

  //文件上传页
  app.get('/upload', checkLogin);
  app.get('/upload', function (req, res) {
    res.render('upload', {
      title: '文件上传',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/upload', checkLogin);
  app.post('/upload', function (req, res) {
    req.flash('success', '文件上传成功!');
    res.redirect('/upload');
  });

  //头像上传页(本地)
  app.get('/avaupload', checkLogin);
  app.get('/avaupload', function (req, res) {
    res.render('avaupload', {
      title: '上传本地头像',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/avaupload', checkLogin);
  app.post('/avaupload', function (req, res) {
    var ava = req.files.avafile.name;
    var pos1 = ava.lastIndexOf('.jpg');
    var pos2 = ava.indexOf('.jpeg');
    var pos3 = ava.lastIndexOf('.bmp');
    var l = ava.length - 4;
    if(pos1 === l || pos2 > -1 || pos3 === l) {
      var head = '/images/' + ava;
      User.aupdate(req.session.user.name, head, function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/avaupload');//出错！返回上传页
    }
      req.flash('success', '头像上传成功!');
      res.redirect('/');//成功！返回主页
    });
    }else {
      req.flash('success', '头像上传失败，请检查图片格式!');
      res.redirect('/avaupload');//上传头像失败，返回上传页
    }
  });

  //头像上传（外链）
  app.get('/ava2upload', checkLogin);
  app.get('/ava2upload', function (req, res) {
    res.render('ava2upload', {
      title: '上传外链头像',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/ava2upload', checkLogin);
  app.post('/ava2upload', function (req, res) {
    var ava = req.body.ava2file;
    var pos1 = ava.lastIndexOf('.jpg');
    var pos2 = ava.indexOf('.jpeg');
    var pos3 = ava.lastIndexOf('.bmp');
    var l = ava.length - 4;
    if(pos1 === l || pos2 > -1 || pos3 === l) {
      var head = ava;
      User.aupdate(req.session.user.name, head, function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/ava2upload');//出错！返回上传页
    }
      req.flash('success', '头像上传成功!');
      res.redirect('/');//成功！返回主页
    });
    }else {
      req.flash('success', '头像上传失败，请检查图片格式!');
      res.redirect('/ava2upload');//上传头像失败，返回上传页
    }
  });

  //文档页，显示所有文章
  app.get('/archive', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      res.render('archive', {
        title: '文档',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //文档页，显示所有原创文章
  app.get('/original', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      res.render('original', {
        title: '文档',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //文档页，显示转载文章
  app.get('/reprint', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      res.render('reprint', {
        title: '文档',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  
  //标签页
  app.get('/tags', function (req, res) {
    Post.getTags(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      res.render('tags', {
        title: '标签',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //进入指定标签
  app.get('/tags/:tag', function (req, res) {
    Post.getTag(req.params.tag, function (err, posts) {
      if (err) {
        req.flash('error',err); 
        return res.redirect('/');//错误，返回主页
      }
      //返回指定标签文章
      res.render('tag', {
        title: '当前标签:' + req.params.tag,
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  /*
  *原定分享页，现为404测试页
  *不存在/share页面
  *找不到页面跳转404页面
  */
  app.get('/share', function (req, res) {
    res.render('share', {
      title: '分享',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  //点击用户名，显示其发布的文章
  app.get('/u/:name', function (req, res) {
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //检查用户是否存在
    User.get(req.params.name, function (err, user) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/');//错误，返回主页
      }
      if (!user) {
        req.flash('error', '用户不存在!'); 
        return res.redirect('/');//不存在该用户，返回主页
      }
      //查询并返回该用户所有文章信息，每页显示3篇
      Post.getThree(user.name, page, function (err, posts, total) {
        if (err) {
          req.flash('error', err); 
          return res.redirect('/');
        }
        res.render('user', {
          title: user.name,
          posts: posts,
          page: page,
          isFirstPage: (page - 1) === 0,
          isLastPage: ((page - 1) * 3 + posts.length) === total,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
      });
    }); 
  });
  
  //点击文章名，查看文章详情
  app.get('/u/:name/:day/:title', function (req, res) {
    Post.getOne(req.params.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');//错误，返回主页
      }
      res.render('article', {
        title: req.params.title,
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //留言
  app.post('/u/:name/:day/:title', function (req, res) {
    User.get(req.session.user.name, function (err, user) {
      //定义留言数据格式
      var date = new Date(),
          time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
               date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
      var comment = {
        name: user.name,
        head: user.head,
        email: user.email,
        website: '/u/' + user.name,
        time: time,
        content: req.body.content
    };
    var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment);
    //将新的留言信息存入数据库
    newComment.save(function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '留言成功!');
      res.redirect('back');//成功，返回上一步操作，并重新加载留言数据
    });
    });
  });

  //编辑文章
  app.get('/edit/:name/:day/:title', checkLogin);
  app.get('/edit/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.edit(currentUser.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');//错误，返回主上一步操作
      }
      res.render('edit', {
        title: '编辑',
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.post('/edit/:name/:day/:title', checkLogin);
  app.post('/edit/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.update(currentUser.name, req.params.day, req.params.title, req.body.post, function (err) {
      var url = encodeURI('/u/' + req.params.name + '/' + req.params.day + '/' + req.params.title);
      if (err) {
        req.flash('error', err); 
        return res.redirect(url);//出错！返回文章页
      }
      req.flash('success', '修改成功!');
      res.redirect(url);//成功！返回文章页
    });
  });

  //删除文章
  app.get('/remove/:name/:day/:title', checkLogin);
  app.get('/remove/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.remove(currentUser.name, req.params.day, req.params.title, function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '删除成功!');
      res.redirect('/');//删除成功，返回主页
    });
  });

  //转载文章
  app.get('/reprint/:name/:day/:title', checkLogin);
  app.get('/reprint/:name/:day/:title', function (req, res) {
    Post.edit(req.params.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');//错误，返回上一步操作
      }
      var currentUser = req.session.user,
          reprint_from = {name: post.name, day: post.time.day, title: post.title},
          reprint_to = {name: currentUser.name, head: currentUser.head};
      Post.reprint(reprint_from, reprint_to, function (err, post) {
        if (err) {
          req.flash('error', err);
          return res.redirect('back');//错误，返回上一步操作
        }
        req.flash('success', '转载成功!');//转载成功返回主页
        res.redirect('/');
      });
    });
  });

  function checkLogin(req, res, next) {//检测是否登陆
    if (!req.session.user) {
      req.flash('error', '未登陆!'); 
      res.redirect('/login');//未登陆，跳转登陆页
    }
    next();
  }

  function checkNotLogin(req, res, next) {//检测是否登出
    if (req.session.user) {
      req.flash('error', '已登陆!'); 
      res.redirect('back');//返回上一步操作
    }
    next();
  }

  //模块1 url监听
  app.get('/m1/:url', checkNotLogin);
  app.get('/m1/:url', function (req, res) {
    res.render(req.params.url, {
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });
  //模块2 url监听
  app.get('/m2/:url', checkLogin);
  app.get('/m2/:url', function (req, res) {
    res.render(req.params.url, {
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });
  
  //主页
  app.get('/m', function (req, res) {
    //判断是否是第一页，并把请求的页数转换成 number 类型
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //查询并返回第 page 页的  5篇文章（不足则全部获取）
    Post.getFive(null, page, function (err, posts, total) {
      if (err) {
        posts = [];
      } 
      res.render('indexm', {
        posts: posts,
        page: page,
        isFirstPage: (page - 1) === 0,
        isLastPage: ((page - 1) * 5 + posts.length) === total,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //进入弹幕页
  app.get('/barragem', function (req, res) {
    Barrage.get(function (err, post) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m');//错误，返回主页
      }
      res.render('barragem', {
        title: '弹幕',
        post:post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //动弹保存
  app.post('/barragem', function (req, res) {
    User.get(req.session.user.name, function (err, user) {
      //定义留言数据格式
      var date = new Date(),
          time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
               date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
      var barrage = {
        name: user.name,
        email: user.email,
        website: '/um/' + user.name,
        time: time,
        content: req.body.content
    };
    var newBarrage = new Barrage(barrage);
    //将新的留言信息存入数据库
    newBarrage.save(function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '动弹成功!');
      res.redirect('back');//成功，返回上一步操作，并重新加载留言数据
    });
    });
  });

  app.post('/m1/regm', checkNotLogin);
  app.post('/m1/regm', function (req, res) {
    var name = req.body.name,
        password = req.body.password,
        password_re = req.body['password-repeat'];
    //检验用户两次输入的密码是否一致
    if (password_re !== password) {
      req.flash('error', '两次输入的密码不一致!'); 
      return res.redirect('/m1/regm');//返回注册页
    }
    //生成密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    var newUser = new User({
        name: req.body.name,
        password: password,
        email: req.body.email
    });
    //检查用户名是否已经存在 
    User.get(newUser.name, function (err, user) {
      if (user) {
        req.flash('error', '用户已存在!');
        return res.redirect('/m1/regm');//返回注册页
      }
      //如果不存在则新增用户
      newUser.save(function (err, user) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/m1/regm');//注册失败返回主册页
        }
        req.session.user = user;//用户信息存入 session
        req.flash('success', '注册成功!');
        res.redirect('/m1/loginm');//注册成功后跳转登陆页
      });
    });
  });

  app.get('/m2/changem', checkLogin);
  app.get('/m2/changem', function (req, res) {
    res.render('changem', {
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/m2/changem', checkLogin);
  app.post('/m2/changem', function (req, res) {
    var ypassword = req.body.ypw,
        password = req.body.xpw,
        password_re = req.body['xpw-2'];

    //检验用户两次输入的密码是否一致
    if (password_re !== password) {
      req.flash('error', '两次输入的密码不一致!');
      return res.redirect('/m2/change');//返回修改页
    }
    //生成原始密码的 md5 值
    var md5 = crypto.createHash('md5'),
        ypassword = md5.update(req.body.ypw).digest('hex');
    //检查密码是否正确
    User.get(req.session.user.name, function (err, user) {
      if (ypassword !== user.password) {
        req.flash('error', '原始密码错误!');
        return res.redirect('/m2/changem');//返回修改页
      }
    //生成新密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.xpw).digest('hex');
    //更新数据库，密码
    User.update(user.name, password, function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m2/changem');//出错！返回修改页
      }
      req.flash('success', '修改成功!');
      res.redirect('/m');//成功！返回主页
    });

    });
  });

  app.post('/m1/loginm', checkNotLogin);
  app.post('/m1/loginm', function (req, res) {
    //生成密码的 md5 值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    //检查用户是否存在
    User.get(req.body.name, function (err, user) {
      if (!user) {
        req.flash('error', '用户不存在!'); 
        return res.redirect('/m1/loginm');//用户不存在则跳转到登陆页
      }
      //检查密码是否一致
      if (user.password !== password) {
        req.flash('error', '密码错误!'); 
        return res.redirect('/m1/loginm');//密码错误则跳转到登陆页
      }
      //用户名密码都匹配后，将用户信息存入 session
      req.session.user = user;
      req.flash('success', '登陆成功!');
      res.redirect('/m');//登陆成功后跳转到主页
    });
  });

  app.post('/m2/postm', checkLogin);
  app.post('/m2/postm', function (req, res) {
    var currentUser = req.session.user,
        tags = [req.body.tag1, req.body.tag2, req.body.tag3],
        post = new Post(currentUser.name, req.body.title, tags, req.body.post);
    post.save(function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/m2/post');//发表失败返回发表页
      }
      req.flash('success', '发布成功!');
      res.redirect('/m');//发表成功跳转到主页
    });
  });

  //登出页
  app.get('/logoutm', checkLogin);//检查是否登录，未登陆返回登陆页
  app.get('/logoutm', function (req, res) {
    req.session.user = null;
    req.flash('success', '登出成功!');
    res.redirect('/m');//登出成功后跳转到主页
  });

  app.post('/m2/avauploadm', checkLogin);
  app.post('/m2/avauploadm', function (req, res) {
    var ava = req.body.ava2file;
    var pos1 = ava.lastIndexOf('.jpg');
    var pos2 = ava.indexOf('.jpeg');
    var pos3 = ava.lastIndexOf('.bmp');
    var l = ava.length - 4;
    if(pos1 === l || pos2 > -1 || pos3 === l) {
      var head = ava;
      User.aupdate(req.session.user.name, head, function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m2/avauploadm');//出错！返回上传页
    }
      req.flash('success', '头像上传成功!');
      res.redirect('/m');//成功！返回主页
    });
    }else {
      req.flash('success', '头像上传失败，请检查图片格式!');
      res.redirect('/m2/avauploadm');//上传头像失败，返回上传页
    }
  });

  //文档页，显示所有文章
  app.get('/archivem', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m');//错误，返回主页
      }
      res.render('archivem', {
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //文档页，显示所有原创文章
  app.get('/originalm', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m');//错误，返回主页
      }
      res.render('originalm', {
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //文档页，显示转载文章
  app.get('/reprintm', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m');//错误，返回主页
      }
      res.render('reprintm', {
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  
  //标签页
  app.get('/tagsm', function (req, res) {
    Post.getTags(function (err, posts) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/m');//错误，返回主页
      }
      res.render('tagsm', {
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //进入指定标签
  app.get('/tagsm/:tag', function (req, res) {
    Post.getTag(req.params.tag, function (err, posts) {
      if (err) {
        req.flash('error',err);
        return res.redirect('/m');//错误，返回主页
      }
      //返回指定标签文章
      res.render('tagm', {
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //点击用户名，显示其发布的文章
  app.get('/um/:name', function (req, res) {
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //检查用户是否存在
    User.get(req.params.name, function (err, user) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('/m');//错误，返回主页
      }
      if (!user) {
        req.flash('error', '用户不存在!');
        return res.redirect('/m');//不存在该用户，返回主页
      }
      //查询并返回该用户所有文章信息，每页显示3篇
      Post.getThree(user.name, page, function (err, posts, total) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/m');
        }
        res.render('userm', {
          posts: posts,
          page: page,
          isFirstPage: (page - 1) == 0,
          isLastPage: ((page - 1) * 3 + posts.length) == total,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
      });
    }); 
  });
  
  //点击文章名，查看文章详情
  app.get('/um/:name/:day/:title', function (req, res) {
    Post.getOne(req.params.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/m');//错误，返回主页
      }
      res.render('articlem', {
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  //留言
  app.post('/um/:name/:day/:title', function (req, res) {
    User.get(req.session.user.name, function (err, user) {
      //定义留言数据格式
      var date = new Date(),
          time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
               date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
      var comment = {
        name: user.name,
        head: user.head,
        email: user.email,
        website: '/um/' + user.name,
        time: time,
        content: req.body.content
    };
    var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment);
    //将新的留言信息存入数据库
    newComment.save(function (err) {
      if (err) {
        req.flash('error', err); 
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '留言成功!');
      res.redirect('back');//成功，返回上一步操作，并重新加载留言数据
    });
    });
  });

  //编辑文章
  app.get('/editm/:name/:day/:title', checkLogin);
  app.get('/editm/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.edit(currentUser.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');//错误，返回主上一步操作
      }
      res.render('editm', {
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.post('/editm/:name/:day/:title', checkLogin);
  app.post('/editm/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.update(currentUser.name, req.params.day, req.params.title, req.body.post, function (err) {
      var url = encodeURI('/um/' + req.params.name + '/' + req.params.day + '/' + req.params.title);
      if (err) {
        req.flash('error', err);
        return res.redirect(url);//出错！返回文章页
      }
      req.flash('success', '修改成功!');
      res.redirect(url);//成功！返回文章页
    });
  });

  //删除文章
  app.get('/removem/:name/:day/:title', checkLogin);
  app.get('/removem/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.remove(currentUser.name, req.params.day, req.params.title, function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');//错误，返回上一步操作
      }
      req.flash('success', '删除成功!');
      res.redirect('/m');//删除成功，返回主页
    });
  });

  //转载文章
  app.get('/reprintm/:name/:day/:title', checkLogin);
  app.get('/reprintm/:name/:day/:title', function (req, res) {
    Post.edit(req.params.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');//错误，返回上一步操作
      }
      var currentUser = req.session.user,
          reprint_from = {name: post.name, day: post.time.day, title: post.title},
          reprint_to = {name: currentUser.name, head: currentUser.head};
      Post.reprint(reprint_from, reprint_to, function (err, post) {
        if (err) {
          req.flash('error', err);
          return res.redirect('back');//错误，返回上一步操作
        }
        req.flash('success', '转载成功!');//转载成功返回主页
        res.redirect('/m');
      });
    });
  });
};